package com.mjp.learn.multi.task;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 利用ReentrantLock condition
 */
public class Test03 {
    public static ReentrantLock lock = new ReentrantLock();
    public static Condition thread1Condition = lock.newCondition();
    public static Condition thread2Condition = lock.newCondition();

    public static void main(String[] args) {
        new Thread(() -> {
            try {
                lock.lock();
                for (int i = 1; i <= 26; i++) {
                    System.out.print(i + " ");
                    thread2Condition.signal();
                    thread1Condition.await();
                }
                thread2Condition.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }).start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {

        }

        new Thread(() -> {
            try {
                lock.lock();
                for (char i = 'A'; i <= 'Z'; i++) {
                    System.out.print(i + " ");
                    thread1Condition.signal();
                    thread2Condition.await();
                }
                thread1Condition.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }).start();
    }
}
